package main

import (
	"embed"
	"erp/models"
	"erp/routers"
	"erp/services"
	"html/template"
	"net/http"
	"os"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

//go:embed static/*
var staticFS embed.FS

//go:embed templates/*
var templatesFS embed.FS

func main() {
	// 初始化GORM
	db, err := gorm.Open(sqlite.Open("erp.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 自动迁移 schema
	db.AutoMigrate(&models.Warehouse{}, &models.Product{}, &models.InventoryRecord{}, &models.SystemSetting{}, &models.EmailReminder{})
	if err := db.AutoMigrate(&models.Warehouse{}, &models.Product{}, &models.InventoryRecord{}, &models.SystemSetting{}, &models.EmailReminder{}); err != nil {
		panic("failed to migrate database: " + err.Error())
	}

	// 初始化系统设置
	initSystemSettings(db)

	// 初始化邮件服务
	// 从数据库读取配置，若未配置则不启动调度器，仅提示
	var settings []models.SystemSetting
	db.Where("setting_key LIKE ?", "email_%").Find(&settings)
	config := make(map[string]string)
	for _, s := range settings {
		config[s.SettingKey] = s.SettingValue
	}

	if config["email_smtp_host"] != "" && config["email_smtp_username"] != "" && config["email_smtp_password"] != "" && config["email_from_email"] != "" {
		port := 465
		if pStr, ok := config["email_smtp_port"]; ok && pStr != "" {
			if p, err := strconv.Atoi(pStr); err == nil {
				port = p
			}
		}
		emailConfig := services.EmailConfig{
			SMTPHost:     config["email_smtp_host"],
			SMTPPort:     port,
			SMTPUsername: config["email_smtp_username"],
			SMTPPassword: config["email_smtp_password"],
			FromEmail:    config["email_from_email"],
			FromName:     config["email_from_name"],
		}
		emailService := services.NewEmailService(emailConfig, db)
		// 启动邮件提醒调度器
		emailService.StartReminderScheduler()
	}

	// 初始化Gin路由器
	router := gin.Default()

	// 设置静态文件目录
	router.StaticFS("/static", http.FS(staticFS))

	// 加载HTML模板
	tmpl, err := template.ParseFS(templatesFS, "templates/*")
	if err != nil {
		panic("failed to parse templates")
	}
	router.SetHTMLTemplate(tmpl)

	// 创建上传目录
	os.MkdirAll("uploads", 0755)

	// 注册路由
	routers.SetupRouter(router, db)

	// 添加图片上传路由
	router.POST("/api/upload", routers.HandleUpload)

	// 添加静态文件服务
	router.Static("/uploads", "./uploads")

	// 启动服务器
	router.Run(":8080")
}

// 初始化系统设置
func initSystemSettings(db *gorm.DB) {
	// 检查是否已存在库房标题设置
	var warehouseTitle models.SystemSetting
	if err := db.Where("setting_key = ?", "warehouse_title").First(&warehouseTitle).Error; err != nil {
		// 不存在则创建
		db.Create(&models.SystemSetting{
			SettingKey:   "warehouse_title",
			SettingValue: "库房",
		})
	}

	// 检查是否已存在物资标题设置
	var productTitle models.SystemSetting
	if err := db.Where("setting_key = ?", "product_title").First(&productTitle).Error; err != nil {
		// 不存在则创建
		db.Create(&models.SystemSetting{
			SettingKey:   "product_title",
			SettingValue: "物资",
		})
	}
}
